﻿/*
 * Created by SharpDevelop.
 * User: Intel
 * Date: 27.11.2014
 * Time: 15:22
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Collections.Generic;

using MySql.Data.MySqlClient;
using Region.Utils;
namespace Region
{
  /// <summary>
  /// Description of Poruch.
  /// </summary>
  [DBObject(Table = "poruch", PrimaryKeyPole = "PoruchID")]
  public class Poruch : DBObject
  {
    const String FileTemplateRTF="Template/Raspor.rtf";
    #region Поля
    [DBColumn]
    public Int32 PoruchID { get { return (Int32)getPole("PoruchID"); } set { setPole("PoruchID", value); } }
    [DBColumn]
    public Int32 OtdelID { get { return (Int32)getPole("OtdelID"); } set { setPole("OtdelID", value); } }
    [DBColumn]
    public Int32 KontID { get { return (Int32)getPole("KontID"); } set { setPole("KontID", value); } }
    [DBColumn]
    public Int32 IspUserID { get { return (Int32)getPole("IspUserID"); } set { setPole("IspUserID", value); } }
    [DBColumn]
    public Int32 PoruchNum { get { return (Int32)getPole("PoruchNum"); } set { setPole("PoruchNum", value); } }
    
        //Date
    [DBColumn(PoleType = EPoleType.Date)]
    public RegionDate LastEditTime { get { return (RegionDate)getPole("LastEditTime"); } set { setPole("LastEditTime", value); } }
    [DBColumn(PoleType = EPoleType.Date)]
    public RegionDate CheckTime { get { return (RegionDate)getPole("CheckTime"); } set { setPole("CheckTime", value); } }
    [DBColumn(PoleType = EPoleType.Date)]
    public RegionDate PoruchDate { get { return (RegionDate)getPole("PoruchDate"); } set { setPole("PoruchDate", value); } }
    
    public Kont Kont { get { return m_engine.getKont(KontID); } set { KontID = value.KontID; } }    
    public Otdel Otdel { get { return m_engine.getOtdel(OtdelID); } set { OtdelID = value.OtdelID; } }    
    public User IspUser { get { return m_engine.getUser(IspUserID); } set { IspUserID = value.UserID; } }
    #endregion   
    #region Переопределённые методы DBObject
    public override bool save()
    {
      //Тут написать действия необходимые перед сохранением полей
      return base.save();
    }
    public override bool isEdit()
    {
      return base.isEdit();
    }
    public override bool read(MySqlConnection RegionDB=null)
    {
      if (!base.read(RegionDB)) return false;
      return true;
    }
    /// <summary>Не редактируемые поля. доступны только для администратор</summary>
    //static private Dictionary<String, bool> Access_NoEdit = new Dictionary<String, bool>() { { "RasporID", true }, { "RasporNum", true }, { "RasporYear", true }, { "StatusVip", true }, { "RucPodpis", true }, { "NachPodpis", true } };
    /// <summary>Поля закрываемые подписью</summary>
    //static private Dictionary<String, bool> Access_BasePoles = new Dictionary<String, bool>() { { "Date", true }, { "CheckDoc", true }, { "CheckGo", true }, { "CheckPlan", true }, { "CheckLicen", true }, { "Pred", true }, { "OsnovID", true }, { "OtdelID", true }, { "IspUserID", true }, { "KontID", true }, { "TP", true }, { "Start", true }, { "End", true }, { "IspInfo", true }, { "ExpertsInfo", true }, { "TargetInfo", true }, { "TaskInfo", true }, { "OsnovInfo", true }, { "MKontrInfo", true }, { "AReglamInfo", true }, { "PDocInfo", true }, { "RucComment", true }, { "NachComment", true }, { "Action_StatusVip", true }, { "Action_RucPodpis", true }, { "Action_NachPodpis", true } };
    public override bool poleCheck(String PoleName, Object Value) { return true; }
    public override bool poleAccess(String PoleName)
    {
      // Администратору вообще многое можно
      RegionDate tc =  CheckTime;
      if (PoleName=="PoruchNum") return false;
      if (PoleName=="PoruchDate") return false;
      //if (m_engine.isAccess("Admin")) return true;
      if (PoleName=="IspUserID") return false;
      if (PoleName=="OtdelID") return false;
      if (IspUserID == m_engine.CurrentUser.UserID) return true;
      return false;//Нет явынх править занчит надо запретить            
    }
    #endregion
    #region Проверяемые объекты
    public class PoruchObject : DBObject
    {
      public Int32 PoruchObjectID { get { return (Int32)getPole("PoruchObjectID"); }}
      public Int32 PoruchID { get { return (Int32)getPole("PoruchID"); }}
      /// <summary>Идентификатор обекта</summary>
      public Int32 KontObjectID { get { return (Int32)getPole("KontObjectID"); } set { setPole("KontObjectID", value); } }
      /// <summary> Флаг обозначающий удалять запись при сохранении </summary>
      public Boolean Del { get; set; }
      #region Переопределённые методы DBObject
      public override bool save()
      {
        if (Del) return delete(); else return base.save();
      }
      public PoruchObject(Engine engine,Int32 PoruchObjectID):base( engine,"poruchobject","PoruchObjectID",PoruchObjectID)
      {
        m_deleteEnable = true;
        addPoles(EPoleType.Int32, new String[] { "PoruchObjectID", "PoruchID", "KontObjectID"});
      }
      #endregion
    }
    //public class RasporObject { public Int32 KontObjectID;}        
    private Dictionary<Int32, PoruchObject> d_PoruchObjects;
    public Dictionary<Int32, PoruchObject> PoruchObjects { get { return new Dictionary<Int32, PoruchObject>(d_PoruchObjects); } }
    public bool AddPoruchObject(Int32 KontObjectID)
    {
      if (d_PoruchObjects.ContainsKey(KontObjectID)) return false;
      MySqlCommand cmd;          
      var Param = new SQLParam();
      Param["@PoruchID"] = PoruchID;
      Param["@KontObjectID"] = KontObjectID;
      m_engine.SQLEdit("INSERT INTO poruchobject(PoruchID,KontObjectID) VALUES (@PoruchID,@KontObjectID)", Param, out cmd);                    
      var PO = new PoruchObject(m_engine,(Int32)cmd.LastInsertedId);
      PO.KontObjectID = KontObjectID;
      d_PoruchObjects[PO.KontObjectID] = PO;
      return true;
    }
    public bool DelPoruchObject(Int32 KontObjectID)
    {
      if (!d_PoruchObjects.ContainsKey(KontObjectID)) return false;
      d_PoruchObjects[KontObjectID].Del = true;
      return true;
    }
    #endregion
    /// <summary>Проверить и получить список ошибок в распоряжении</summary><returns>Список ошибок</returns>
    public List<String> check()
    {
      List<String> L = new List<string>();
      return L;
    }
    /// <summary>Экспорт в RTF</summary><param name="OutFile">Имя экспортируемого файла</param><returns>true - экспорт удался</returns>
    public bool exportRTF(String OutFile)
    {
        var Poles = new Dictionary<String, Object>();
        Poles["Ispoln"] = m_engine.getUser(IspUserID).FIO + ", " + m_engine.getUser(IspUserID).Titul + @" \line " + m_engine.getUser(IspUserID).Telefon;
        if (Poles["Podpis"] == null) Poles["Podpis"] = " \n ";
        return Utils.Export.export("rtf",File.ReadAllBytes(FileTemplateRTF), OutFile, Poles, null);
    }
    public Poruch(Engine engine, Int32 PoruchID)
        : base(engine,  PoruchID)
    {      
      d_PoruchObjects = new Dictionary<Int32,PoruchObject>();
    }
    /*
    public override void showEditor()
    {
      var F = new Forms.PoruchForm(m_engine, PoruchID);
      F.ShowDialog();
    }*/
  }
  /// <summary> Класс RasporList обеспечивает работу со списками распоряжиний </summary>
  public struct PoruchListLine
  {
    public Int32 PoruchID;
    public Int32 OtdelID;
    public String IspFIO;
    public bool Check;
  }
  public class PoruchList:DBList<PoruchListLine>
  { 
    void _ExportListXMLX_Task(Object Param, TaskManager.Task task) {ExportListXMLX((String)Param,task);}
    public TaskManager.Task ExportListXMLX_Task(String FileName){ return m_engine.taskManager.addTask(_ExportListXMLX_Task,"Формирование реестра распоряжеиний", FileName);}
    public bool ExportListXMLX(String FileName, TaskManager.Task task = null)
    {
      /*var EL = new List<Dictionary<String,Object>>();
      var Raions = m_engine.Raions;
      var KT = m_engine.KontType;
      var Osnov = m_engine.Osnov;
      var Otdels = m_engine.Otdels;
      setWhere("IgnorePage", true);
      var old_lines = new List<PoruchListLine>(m_lines);
      if (task!=null) task.TaskName = "Чтение из базы данных";
      Filter();
      var YNN_List = new Dictionary<Int32,String>(){{0,"Нет"},{1,"Да"},{-1,"[Не указан]"}};
      var NNar_List = new Dictionary<Int32,String>(){{0,"Выявлены"},{1,"Не выявлены"},{-1,"[Не указано]"}};
      if (task!=null)
      {
      	task.TaskName = "Формирование реестра распоряжеиний";
      	task.TaskMax = m_lines.Count;
      	task.TaskValue = 0;
      }
      foreach(PoruchListLine line in m_lines)
      {
        var ExportLine = new Dictionary<String,Object>();
        var Raspor = m_engine.getRaspor(line.RasporID);
        
        ExportLine["%RasporNum%"] = Raspor.RasporNum;
        ExportLine["%Date%"] = Raspor.Date;
        ExportLine["%CheckDoc%"] = Raspor.CheckDoc?"Документарная":"";
        ExportLine["%CheckGo%"] = Raspor.CheckGo?"Выездная":"";
        ExportLine["%CheckPlan%"] = Raspor.CheckPlan?"Плановая":"Внеплановая";
        ExportLine["%CheckLicen%"] = Raspor.CheckLicen?"По лицензионному контролю":"";
        if (Raspor.KontID>0)
        {
          var Kont = m_engine.getKont(Raspor.KontID);
          ExportLine["%KontName%"] = Kont.KontName;
          ExportLine["%INN%"] = Kont.INN;
          ExportLine["%OGRN%"] = Kont.OGRN;
          ExportLine["%KontType%"] = KT[Kont.KontTypeID];
          ExportLine["%KontULAddress%"] = Kont.KontULAddress;
          ExportLine["%KontFKAddress%"] = Kont.KontFKAddress;
          ExportLine["%KontGosReg%"] = Kont.KontGosReg;
          ExportLine["%ObjectList%"] = "";
          var KontObjecs = Kont.KontObjects;
          foreach(var RasporObject in Raspor.RasporObjects)
            if (KontObjecs.ContainsKey(RasporObject.Value.KontObjectID))
          {                            
            var KontObject = KontObjecs[RasporObject.Value.KontObjectID];
            ExportLine["%ObjectList%"] +=  KontObject.KontObjectName + ", " + Engine.getAddressString(KontObject.KontObjectPostIndex,KontObject.KontObjectRegion,Raions[KontObject.KontObjectRaionID],KontObject.KontObjectGorod,KontObject.KontObjectNaspunkt,KontObject.KontObjectStreet,KontObject.KontObjectDom,KontObject.KontObjectKorpus,KontObject.KontObjectKvart)+"("+m_engine.KontDirect[KontObject.KontObjectDirect]+")"+";\n";
          }   
        }
        ExportLine["%IspInfo%"] = Raspor.IspInfo;
        ExportLine["%ExpertsInfo%"] = Raspor.ExpertsInfo;
        ExportLine["%TargetInfo%"] = Raspor.TargetInfo;
        ExportLine["%TaskInfo%"] = Raspor.TaskInfo;
        
        ExportLine["%TP%"] = Raspor.TP;
        ExportLine["%Start%"] = Raspor.Start;
        ExportLine["%End%"] = Raspor.End;
        ExportLine["%Osnov%"] = Osnov[Raspor.OsnovID];
        ExportLine["%OsnovInfo%"] = Raspor.OsnovInfo;
        ExportLine["%MKontrInfo%"] = Raspor.MKontrInfo;
        ExportLine["%AReglamInfo%"] = Raspor.AReglamInfo;
        ExportLine["%PDocInfo%"] = Raspor.PDocInfo;
        ExportLine["%Status%"] = Raspor.StatusVip?"Выполнено":"Черновик";            
        ExportLine["%IspUser%"] = m_engine.getUser(Raspor.IspUserID).FIO;
        ExportLine["%Otdel%"] = Otdels[Raspor.OtdelID].OtdelName;
        ExportLine["%NachPodpis%"] = Raspor.NachPodpis==0?"":m_engine.getUser(Raspor.NachPodpis).FIO;
        ExportLine["%RucPodpis%"] = Raspor.RucPodpis==0?"":m_engine.getUser(Raspor.RucPodpis).FIO;
        ExportLine["%Procuror%"] = Raspor.Procuror;
        ExportLine["%Del%"] = Raspor.Del;
        //результаты
        ExportLine["%AktDate%"] = Raspor.AktDate;
        ExportLine["%FStart%"] = Raspor.FStart;
        ExportLine["%FEnd%"] = Raspor.FEnd;
        ExportLine["%PredpisDate%"] = Raspor.PredpisDate;
        ExportLine["%ControlDate%"] = Raspor.ControlDate;
        ExportLine["%PredpisFull%"] = YNN_List[Raspor.PredpisFull];
        ExportLine["%PredpisTime%"] = YNN_List[Raspor.PredpisTime];
        ExportLine["%NNar%"] = NNar_List[Raspor.NNar];
        
        ExportLine["%NumNar%"] = Raspor.NumNar;
        ExportLine["%Predstav%"] = YNN_List[Raspor.Predstav];
        ExportLine["%NStop%"] = YNN_List[Raspor.NStop];
        Dictionary<Int32,Protokol> Protokols = Raspor.Protokols;
        Int32 SumP=0, SumP2=0;
        String ListProtokol = "";
        var Article = m_engine.Article;
        foreach(var P in Protokols)
        {
          String Info ="";
          if (P.Value.MeasureID==1) Info += " штраф "+P.Value.SumP.ToString();
          if (P.Value.MeasureID==2) Info += " предупреждение ";
          if (P.Value.MeasureSudID==4 || P.Value.MeasureSudID==5) Info += " суд:штраф  "+P.Value.SumP.ToString();
          if (P.Value.MeasureSudID==1 ) Info += " суд:предупреждение  ";
          if (P.Value.MeasureSudID==6 || P.Value.MeasureSudID==7) Info += " суд:Приостановление деятельности  ";
          ListProtokol += "№"+P.Value.ProtokolNum + " от " + P.Value.ProtokolReg.ToShortDateString()+ " " + Article[P.Value.ArticleID]+Info+";\n";
          SumP+=P.Value.SumP;
          SumP2+=P.Value.SumP2;
        }
        Int32 RasporUserTime=0;
        String RasporUserTimeList="";
        foreach(var u in Raspor.RasporUsers)
        {
        	RasporUserTimeList += u.Value.User.FIO + " "+  (u.Value.WorkTime/60.0).ToString()+" ч.;\n";
        	RasporUserTime+= u.Value.WorkTime;
        }
        ExportLine["%RasporUserTime%"] = RasporUserTime/60;
        ExportLine["%RasporUserTimeList%"] = RasporUserTimeList;
        ExportLine["%NumProtokol%"] = Protokols.Count;
        ExportLine["%ListProtokol%"] = ListProtokol;
        ExportLine["%ProtokolSumP%"] = SumP;
        ExportLine["%ProtokolSumP2%"] = SumP2;
        ExportLine["%NLic%"] = YNN_List[Raspor.NLic];
        ExportLine["%SLic%"] = YNN_List[Raspor.SLic];
        ExportLine["%SudZ1%"] = Raspor.SudZ1;
        ExportLine["%SudZ2%"] = Raspor.SudZ2;
        ExportLine["%Nar1%"] = YNN_List[Raspor.Nar1];
        ExportLine["%Nar2%"] = YNN_List[Raspor.Nar2];
        ExportLine["%Nar3%"] = YNN_List[Raspor.Nar3];
        ExportLine["%SudK1%"] = Raspor.SudK1;
        ExportLine["%SudK2%"] = Raspor.SudK2;
        ExportLine["%SudK3%"] = Raspor.SudK3;
        EL.Add(ExportLine);
        if (task!=null) task.TaskValue += 1;
      }      
      setWhere("IgnorePage", false);
      m_lines=old_lines;
      var Template = m_engine.getRegionFile("ReestrRaspor","xlsx");
      var Poles = new Dictionary<String,Object>();
      var Tables = new Dictionary<String,List<Dictionary<String,Object>>>(){{"%RasporNum%",EL}};
      Export.export("xlsx",Template,FileName,Poles,Tables, task);*/
      return true;
    }
    
    public PoruchList(Engine engine):base(engine)
    {
      DefaultPoles.Add("poruch.PoruchID");
      DefaultPoles.Add("poruch.OtdelID");
      DefaultPoles.Add("poruch.CheckTime");
      DefaultPoles.Add("poruch.LastEditTime");
      DefaultPoles.Add("isp.FIO AS IspFIO");
      DefaultTables.Add("poruch");      
      DefaultTables.Add("LEFT JOIN users AS isp ON isp.UserID=poruch.IspUserID");
      DefaultOrderBy.Add("poruch.PoruchID DESC");
    }
    protected override void ProceessWheres(SQLParam Params,List<String> Tables, List<String> Poles,List<String> Wheres,List<String> OrderBy)
    {
      Int32 PoruchID, ParentOtdelID,  IspUserID,RasporUserID;
      
      if (m_wheres.ContainsKey("PoruchID") && m_wheres["PoruchID"] != null && Int32.TryParse(m_wheres["PoruchID"].ToString(), out PoruchID))
      {
        Wheres.Add("poruch.PoruchID=@PoruchID");
        Params["@PoruchID"] = PoruchID;
      }
      if (m_wheres.ContainsKey("ParentOtdelID") && m_wheres["ParentOtdelID"] != null && Int32.TryParse(m_wheres["ParentOtdelID"].ToString(), out ParentOtdelID))
      {
        Tables.Add("INNER JOIN otdel_otdel ON otdel_otdel.OtdelID=poruch.OtdelID");
        Wheres.Add("otdel_otdel.ParentOtdelID=@ParentOtdelID");
        Params["@ParentOtdelID"] = ParentOtdelID;
      }
      if (m_wheres.ContainsKey("IspUserID") && m_wheres["IspUserID"] != null && Int32.TryParse(m_wheres["IspUserID"].ToString(), out IspUserID) && IspUserID>0)
      {
        Wheres.Add("poruch.IspUserID=@IspUserID");
        Params["@IspUserID"] = IspUserID;
      }
    }    
    protected override PoruchListLine readLine(Dictionary<String, Object> r)
    {
      var l = new PoruchListLine();
        l.PoruchID = (Int32)r["PoruchID"];
        l.OtdelID = (Int32)r["OtdelID"];
        try { l.IspFIO = Engine.RegionStringToString((String)r["IspFIO"]); }
        catch { l.IspFIO = ""; }        
        l.Check = false;
      return l;
    }    
  }
  public struct PoruchFunPartListLine
  {
    public String PoruchFunPart;
    public String PoruchFunPartName;
    public String PoruchFunPartComment;
    public String ParentPoruchFunPart;
  }
  public class PoruchFunPartList:DBList<PoruchFunPartListLine>
  { 
    public PoruchFunPartList(Engine engine):base(engine)
    {
      DefaultPoles.Add("poruchfunpart.PoruchFunPart");
      DefaultPoles.Add("poruchfunpart.PoruchFunPartName");
      DefaultPoles.Add("poruchfunpart.PoruchFunPartComment");
      DefaultPoles.Add("poruchfunpart.ParentPoruchFunPart");
      DefaultTables.Add("poruchfunpart");            
      DefaultOrderBy.Add("poruchfunpart.PoruchFunPart ASC");
    }
    protected override void ProceessWheres(SQLParam Params,List<String> Tables, List<String> Poles,List<String> Wheres,List<String> OrderBy)
    {
      
    }    
    protected override PoruchFunPartListLine readLine(Dictionary<String, Object> r)
    {
      var l = new PoruchFunPartListLine();
      l.PoruchFunPart = (String)r["PoruchFunPart"];
      l.PoruchFunPartName = (String)r["PoruchFunPartName"];
      l.PoruchFunPartComment = (String)r["PoruchFunPartComment"];
      l.ParentPoruchFunPart = (String)r["ParentPoruchFunPart"];
      return l;
    }    
  }
  public struct PoruchFunListLine
  {    
    public String PoruchFunID;
    public String PoruchFunPart;
    public String PoruchFun;
    public String PoruchFunComment;
  }
  public class PoruchFunList:DBList<PoruchFunListLine>
  { 
    public PoruchFunList(Engine engine):base(engine)
    {
      DefaultPoles.Add("poruchfun.PoruchFunID");
      DefaultPoles.Add("poruchfun.PoruchFunPart");
      DefaultPoles.Add("poruchfun.PoruchFun");
      DefaultPoles.Add("poruchfun.PoruchFunComment");
      DefaultTables.Add("poruchfun");            
      DefaultOrderBy.Add("poruchfun.PoruchFunID ASC");
    }
    protected override void ProceessWheres(SQLParam Params,List<String> Tables, List<String> Poles,List<String> Wheres,List<String> OrderBy)
    {
      
    }    
    protected override PoruchFunListLine readLine(Dictionary<String, Object> r)
    {
      var l = new PoruchFunListLine();
      l.PoruchFunID = (String)r["PoruchFunID"];
      l.PoruchFunPart = (String)r["PoruchFunPart"];
      l.PoruchFun = (String)r["PoruchFun"];
      l.PoruchFunComment = (String)r["PoruchFunComment"];
      return l;
    }    
  }
  public partial class Engine
  {
      /// <summary> Список открытых поручений </summary>
      private Dictionary<Int32, Poruch> l_Poruch;
      /// <summary> Получить распоряжение по его идентификатору</summary><param name="PoruchID">ИД Распоряжения</param><returns>Объект распоряжения</returns>
      public Poruch getPoruch(Int32 PoruchID)
      {
        if (l_Poruch == null) l_Poruch = new Dictionary<Int32, Poruch>();
        if (l_Poruch.ContainsKey(PoruchID)) return (Poruch)l_Poruch[PoruchID];
        var poruch = new Poruch(this, PoruchID);
        l_Poruch[PoruchID] = poruch;
        return poruch;
      }
      /// <summary>Создать новое распоряжение</summary><param name="BaseRasporID">Идентификатор распоряжения на основе которого создаётся распоряжение</param><returns>Идентификатор нового расоряжения</returns>
      public Int32 newPoruch(Int32 BasePoruchID)
      {
        var Param = new SQLParam();
        //Param["@RasporYear"] = DateTime.Now.Year;
        Param["@IspUserID"] = CurrentUser.UserID;
        Param["@OtdelID"] = CurrentUser.OtdelID;
        var Poles = new String[] { /*"CheckPlan", "CheckDoc", "CheckGo", "ExpertsInfo", "TargetInfo", "TaskInfo", "Pred", "TP", "OsnovID", "MKontrInfo", "AReglamInfo", "PDocInfo", "OsnovInfo" /**/};
        var SqlPoles = new String[0];
        String SqlPolesN = "";
        //foreach (String Pole in Poles) Param["@" + Pole] = "";

        if (BasePoruchID > 0)
        {
          Poruch poruch = getPoruch(BasePoruchID);
          SqlPoles = Poles;
          IDictionary<String, Object> rPoles = poruch.getPoles();
          foreach (String Pole in Poles)
          {
            Param["@" + Pole] = rPoles[Pole];
            SqlPolesN += ", @" + Pole + " AS " + Pole;
          }
        }
        MySqlCommand cmd;
SQLEdit(@"
INSERT INTO poruch(PoruchNum,PoruchDate,IspUserID,OtdelID " + ((SqlPoles.Length > 0) ? ", " : "") + String.Join(" ,", SqlPoles) + @") 
SELECT R1.PoruchNum+1 AS PoruchNum, NOW() AS PoruchDate,
@IspUserID AS IspUserID, @OtdelID AS OtdelID " + SqlPolesN + @"
FROM poruch AS R1 
LEFT JOIN poruch AS R2 ON (R2.PoruchNum=R1.PoruchNum+1 AND YEAR(R2.PoruchDate)=YEAR(NOW())) 
WHERE R2.PoruchNum IS NULL AND YEAR(R1.PoruchDate)=YEAR(NOW())
ORDER BY R1.PoruchNum 
LIMIT 1", Param, out cmd);
        return (Int32)cmd.LastInsertedId;
      }
      /// <summary>Удалить поручение</summary><param name="RasporID">ИД распоряжения</param><returns>true - если распоряжение было удалено</returns>
      public bool delPoruch(Int32 PoruchID)
      {
        Poruch raspor = getPoruch(PoruchID);
        if (!CurrentUser.isAccess("EditRaspor")) return false;// Пользователь неимеет права удалять распоряжения            
        if (!CurrentUser.isAccess("Admin") && CurrentUser.OtdelID != raspor.OtdelID && !Otdels[CurrentUser.OtdelID].isSubOtdel(raspor.OtdelID)) return false;//нельзя удалить черновик другово отдела
        var Param = new SQLParam();
        Param["PoruchID"] = PoruchID;
        //Удалить само распоряжение
        Int32 N = SQLEdit("DELETE FROM poruch WHERE PoruchID=@PoruchID AND CheckTime='0000-00-00 00:00:00'", Param);
        if (N == 1) // Распоряжение действительно удалено. 
        {
          l_Raspor.Remove(PoruchID);
          return true;
        }
        return false;
      }
  }
  
}
